package com.xinggq.user.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinggq.common.context.UserContext;
import com.xinggq.common.enums.EnableEnum;
import com.xinggq.common.exception.AbstractCommonException;
import com.xinggq.user.api.dto.userrole.UserRoleCreateRequest;
import com.xinggq.user.api.dto.userrole.UserRoleVO;
import com.xinggq.user.service.entity.SysRoleEntity;
import com.xinggq.user.service.entity.SysUserEntity;
import com.xinggq.user.service.entity.SysUserRoleEntity;
import com.xinggq.user.service.mapper.SysRoleMapper;
import com.xinggq.user.service.mapper.SysUserMapper;
import com.xinggq.user.service.mapper.SysUserRoleMapper;
import com.xinggq.user.service.service.UserRoleService;
import java.util.ArrayList;
import java.util.Set;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.util.CollectionUtils;

/**
 * 用户角色关联服务实现类
 *
 * @author system
 * @since 2025-01-10
 */
@Service
@Slf4j
@AllArgsConstructor
public class UserRoleServiceImpl implements UserRoleService {

  private final SysUserRoleMapper userRoleMapper;
  private final SysUserMapper userMapper;
  private final SysRoleMapper roleMapper;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public UserRoleVO createUserRole(UserRoleCreateRequest request) {

    request.setAssignedBy(UserContext.getCurrentUserId());
    // 校验用户是否存在
    validateUserExists(request.getUserId());

    // 校验角色是否存在
    validateRoleExists(request.getRoleId());

    // 校验关联是否已存在
    validateUserRoleNotExists(request.getUserId(), request.getRoleId());

    // 创建用户角色关联
    SysUserRoleEntity userRoleEntity = buildUserRoleEntity(request);
    userRoleMapper.insert(userRoleEntity);

    log.info("用户角色关联创建成功，关联ID: {}", userRoleEntity.getId());
    return convertToVO(userRoleEntity);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean deleteUserRole(Long userId) {
    log.info("删除用户角色关联，关联用户ID: {}", userId);
    // 执行删除
    LambdaQueryWrapper<SysUserRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(SysUserRoleEntity::getUserId, userId);
    int result = userRoleMapper.delete(queryWrapper);
    log.info("用户角色关联删除完成，关联ID: {}, 删除结果: {}", userId, result > 0);
    return result > 0;
  }

  @Override
  public List<UserRoleVO> getUserRoles(Long userId) {

    LambdaQueryWrapper<SysUserRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(SysUserRoleEntity::getUserId, userId);

    List<SysUserRoleEntity> userRoleList = userRoleMapper.selectList(queryWrapper);
    if(CollectionUtils.isEmpty(userRoleList)){
      return new ArrayList<>();
    }
    List<UserRoleVO> userRoleVos = new ArrayList<>(userRoleList.size());
    // 获取所有角色ID
    List<Long> roleIds = userRoleList.stream().map(SysUserRoleEntity::getRoleId).toList();
    List<SysRoleEntity> roles = roleMapper.selectByIds(roleIds);
    Map<Long, SysRoleEntity> roleMap = roles.stream().collect(Collectors.toMap(SysRoleEntity::getId, r->r));
    // 获取所有设置人ID
    Set<Long> assignedByUserIds = userRoleList.stream().map(SysUserRoleEntity::getAssignedBy).collect(Collectors.toSet());
    assignedByUserIds.add(userId);
    // 查询所有用户信息
    List<SysUserEntity> assignedByUsers = userMapper.selectByIds(assignedByUserIds);
    Map<Long, SysUserEntity> assignedByUserMap = assignedByUsers.stream().collect(Collectors.toMap(SysUserEntity::getId, u->u));
    userRoleList.forEach(e->{
      UserRoleVO userRoleVO = convertToVO(e);
      userRoleVO.setRoleName(roleMap.get(e.getRoleId()).getRoleName());
      userRoleVO.setRoleCode(roleMap.get(e.getRoleId()).getRoleCode());
      userRoleVO.setAssignedByName(assignedByUserMap.get(e.getAssignedBy()).getRealName());
      userRoleVO.setUsername(assignedByUserMap.get(e.getAssignedBy()).getUsername());
      userRoleVO.setRealName(assignedByUserMap.get(e.getAssignedBy()).getRealName());
      userRoleVos.add(userRoleVO);
    });
    return userRoleVos;
  }

  @Override
  public List<UserRoleVO> getRoleUsers(Long roleId) {

    LambdaQueryWrapper<SysUserRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(SysUserRoleEntity::getRoleId, roleId)
        .eq(SysUserRoleEntity::getStatus, 1);

    List<SysUserRoleEntity> userRoleList = userRoleMapper.selectList(queryWrapper);
    if(CollectionUtils.isEmpty(userRoleList)){
      return new ArrayList<>();
    }
    List<UserRoleVO> userRoleVos = new ArrayList<>(userRoleList.size());
    // 获取所有角色ID
    List<Long> roleIds = userRoleList.stream().map(SysUserRoleEntity::getRoleId).toList();
    List<SysRoleEntity> roles = roleMapper.selectByIds(roleIds);
    Map<Long, SysRoleEntity> roleMap = roles.stream().collect(Collectors.toMap(SysRoleEntity::getId, r->r));
    // 获取所有设置人ID
    Set<Long> assignedByUserIds = userRoleList.stream().map(SysUserRoleEntity::getAssignedBy).collect(Collectors.toSet());
    // 查询所有用户信息
    List<SysUserEntity> assignedByUsers = userMapper.selectByIds(assignedByUserIds);
    Map<Long, SysUserEntity> assignedByUserMap = assignedByUsers.stream().collect(Collectors.toMap(SysUserEntity::getId, u->u));
    userRoleList.forEach(e->{
      UserRoleVO userRoleVO = convertToVO(e);
      userRoleVO.setRoleName(roleMap.get(e.getRoleId()).getRoleName());
      userRoleVO.setRoleCode(roleMap.get(e.getRoleId()).getRoleCode());
      userRoleVO.setAssignedByName(assignedByUserMap.get(e.getAssignedBy()).getRealName());
      userRoleVO.setUsername(assignedByUserMap.get(e.getAssignedBy()).getUsername());
      userRoleVO.setRealName(assignedByUserMap.get(e.getAssignedBy()).getRealName());
      userRoleVos.add(userRoleVO);
    });
    return userRoleVos;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean deleteUserRolesByUserId(Long userId) {
    LambdaQueryWrapper<SysUserRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(SysUserRoleEntity::getUserId, userId);

    int result = userRoleMapper.delete(queryWrapper);
    log.info("批量删除用户角色关联完成，用户ID: {}, 删除数量: {}", userId, result);
    return result > 0;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean deleteUserRolesByRoleId(Long roleId) {
    LambdaQueryWrapper<SysUserRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(SysUserRoleEntity::getRoleId, roleId);

    int result = userRoleMapper.delete(queryWrapper);
    log.info("批量删除角色用户关联完成，角色ID: {}, 删除数量: {}", roleId, result);

    return result > 0;
  }

  /**
   * 校验用户是否存在
   */
  private void validateUserExists(Long userId) {
    LambdaQueryWrapper<SysUserEntity> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(SysUserEntity::getId, userId)
        .ne(SysUserEntity::getStatus, EnableEnum.D.getCode());

    long count = userMapper.selectCount(queryWrapper);
    if (count == 0) {
      throw AbstractCommonException.dataNotFound("用户不存在");
    }
  }

  /**
   * 校验角色是否存在
   */
  private void validateRoleExists(Long roleId) {
    LambdaQueryWrapper<SysRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(SysRoleEntity::getId, roleId)
        .ne(SysRoleEntity::getStatus, -1);

    long count = roleMapper.selectCount(queryWrapper);
    if (count == 0) {
      throw AbstractCommonException.dataNotFound("角色");
    }
  }

  /**
   * 校验用户角色关联是否已存在
   */
  private void validateUserRoleNotExists(Long userId, Long roleId) {
    LambdaQueryWrapper<SysUserRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(SysUserRoleEntity::getUserId, userId)
        .eq(SysUserRoleEntity::getRoleId, roleId);

    long count = userRoleMapper.selectCount(queryWrapper);
    if (count > 0) {
      throw AbstractCommonException.dataExists("用户角色关联");
    }
  }

  /**
   * 构建用户角色关联实体
   */
  private SysUserRoleEntity buildUserRoleEntity(UserRoleCreateRequest request) {
    SysUserRoleEntity entity = new SysUserRoleEntity();
    entity.setUserId(request.getUserId());
    entity.setRoleId(request.getRoleId());
    entity.setAssignedBy(request.getAssignedBy());
    entity.setAssignedAt(LocalDateTime.now());
    // 默认正常状态
    entity.setStatus(EnableEnum.Y.getCode());
    return entity;
  }


  /**
   * 转换为VO（基础信息）
   */
  private UserRoleVO convertToVO(SysUserRoleEntity entity) {
    UserRoleVO vo = new UserRoleVO();
    vo.setId(entity.getId());
    vo.setUserId(entity.getUserId());
    vo.setRoleId(entity.getRoleId());
    vo.setAssignedBy(entity.getAssignedBy());
    vo.setAssignedAt(entity.getAssignedAt());
    vo.setStatus(entity.getStatus());
    return vo;
  }

}